  //
//  ICMBalanceResearchViewController.m
//  ICrEAM
//
//  Created by kuroro on 16/11/24.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ICMBalanceResearchViewController.h"
#import "ICMProxySearchModel.h"
#import "ICMBalanceResearchViewCell.h"
#import "ICMTitleTextFeildView.h"
#import "ICMDatePickerView.h"
#import "NSDate+convenience.h"
#import "ICMBalanceViewController.h"
#import "ICMBalanceBasicInfoModel.h"
#import "ICMRepairMaintenanceModel.h"
#import "ICMRepairPartsModel.h"
#import "PACACalendarView.h"

@interface ICMBalanceResearchViewController ()<UITextFieldDelegate,ICMDatePickerViewDelegate,ICMBalanceResearchViewCellDelegate,PACACalendarViewDelegate>
@property (nonatomic,strong) UITableView *balanceSearchList;
//日历
@property (nonatomic, strong) ICMTitleTextFeildView *labelFrom;
@property (nonatomic, strong) ICMTitleTextFeildView *labelTo;
@property (nonatomic,strong) PACACalendarView *pickerFrom;
@property (nonatomic,strong) PACACalendarView *pickerTo;
@property (nonatomic, strong) NSDate *selectedDateFrom;
@property (nonatomic, strong) NSDate *selectedDateTo;

@property (nonatomic, strong) UITextField * searchText;

//活动数据
@property (nonatomic, strong) NSMutableArray *activityModels;

//上拉加载判断
@property (nonatomic, assign) BOOL hasNext;
@property (nonatomic, assign) int pageNo;

//条件搜索
@property (nonatomic, assign) BOOL isSearchByDate;
//首次进入
@property (nonatomic, assign) BOOL isFirst;
@end

@implementation ICMBalanceResearchViewController

-(NSMutableArray *)activityModels{
    if (!_activityModels) {
        _activityModels = [NSMutableArray array];
    }
    return _activityModels;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isSearchByDate = NO;
    self.isFirst = YES;
    //[self didClickCellWithRO_NO:@"201201-0381" type:@"1"];
    self.navigationItem.title=@"待结算查询";
    self.edgesForExtendedLayout=UIRectEdgeNone;
    // Do any additional setup after loading the view from its nib.
    UIView *topBar = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ActualHeight(40))];
    
    topBar.backgroundColor = Color(0xE5EBEB);
    
    self.view.backgroundColor = BackgroundColor_White;
   
    
    //委托书查询
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(ActualWidth(80), 0, ActualWidth(100), ActualHeight(40))];
    
    title.text = @"待结算查询";
    title.textColor = TitleColor;
    title.textAlignment = NSTextAlignmentCenter;
    title.font = NaviFont;
    
    [topBar addSubview:title];
    
    UIView *underLine = [[UIView alloc]initWithFrame:CGRectMake(ActualWidth(80), ActualHeight(39), ActualWidth(100), 1)];
    
    underLine.backgroundColor = TitleColor;
    
    [topBar addSubview:underLine];
    
    [self.view addSubview:topBar];
    
    //搜索框
    UIView *searchView = [[UIView alloc]initWithFrame:CGRectMake(ScreenWidth-ActualWidth(400), ActualHeight(4), ActualWidth(360), ActualHeight(32))];
    
    searchView.backgroundColor = [UIColor whiteColor];
    searchView.layer.cornerRadius = ActualHeight(32)/2;
    
    UIImageView *searchImage = [[UIImageView alloc]initWithFrame:CGRectMake(ActualWidth(4), ActualHeight(2), ActualWidth(28), ActualHeight(28))];
    
    searchImage.image = [UIImage imageNamed:GetCar_SearchIcon];
    
    [searchView addSubview:searchImage];
    
    UITextField * searchText = [[UITextField alloc]initWithFrame:CGRectMake(ActualWidth(32), 0, ActualWidth(360)-ActualWidth(32), ActualHeight(32))];
    searchText.delegate = self;
    searchText.returnKeyType = UIReturnKeySearch;
    searchText.placeholder = @"车牌号,送修人姓名,送修人手机,服务顾问";
    searchText.font = [UIFont systemFontOfSize:14];
    [searchView addSubview:searchText];
    self.searchText = searchText;
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:) name:@"UITextFieldTextDidChangeNotification" object:self.searchText];
    
    [self.view addSubview:searchView];
    
    //headerview
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, ActualHeight(40), ScreenWidth, ActualHeight(95))];
    
    self.labelFrom = [ICMTitleTextFeildView createClickableICMTitleTextFeildViewWithFrame:CGRectMake(ActualWidth(75), ActualHeight(10), ActualWidth(150), ActualHeight(75)) title:@"开单时间" addTarget:self selector:@selector(clickCalenderBtnFrom)];
    
    UIButton *btnFrom = [[UIButton alloc]initWithFrame:CGRectMake(self.labelFrom.rightEdge+2, ActualHeight(40), ActualWidth(30), ActualWidth(30))];
    [btnFrom addTarget:self action:@selector(clickCalenderBtnFrom) forControlEvents:UIControlEventTouchUpInside];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ActualHeight(30), ActualWidth(30))];
    imageView.image = [UIImage imageNamed:Appointment_Calendar];
    [btnFrom addSubview:imageView];
    
    UILabel *labelText = [[UILabel alloc]initWithFrame:CGRectMake(btnFrom.rightEdge+10, btnFrom.y, ActualWidth(30), ActualHeight(30))];
    
    labelText.text = @"至";
    labelText.textColor = Color(0x666666);
    
    self.labelTo = [ICMTitleTextFeildView createClickableICMTitleTextFeildViewWithFrame:CGRectMake(labelText.rightEdge+10, ActualHeight(10), ActualWidth(150), ActualHeight(75)) title:@"" addTarget:self selector:@selector(clickCalenderBtnTo)];
    
    UIButton *btnTo = [[UIButton alloc]initWithFrame:CGRectMake(self.labelTo.rightEdge+2, ActualWidth(40), ActualWidth(30), ActualWidth(30))];
    [btnTo addTarget:self action:@selector(clickCalenderBtnTo) forControlEvents:UIControlEventTouchUpInside];
    UIImageView *imageViewTo = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ActualHeight(30), ActualWidth(30))];
    imageViewTo.image = [UIImage imageNamed:Appointment_Calendar];
    
    self.labelTo.backgroundColor = Color(0xF4F5F7);
    self.labelFrom.contentText = [ICrEAMTool getNowDate];
    self.labelTo.contentText = [ICrEAMTool getNowDate];
    
    [btnTo addSubview:imageViewTo];
    
    
    UIButton *btnSearch = [[UIButton alloc]initWithFrame:CGRectMake(btnTo.rightEdge+ActualWidth(30), ActualHeight(20), ActualWidth(50), ActualHeight(60))];
    
    [btnSearch addTarget:self action:@selector(searchByDate) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *imageViewSearch = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ActualWidth(30), ActualHeight(30))];
    imageViewSearch.image = [UIImage imageNamed:Appointment_SearchBtn];
    
    UILabel *labelSearch = [[UILabel alloc]initWithFrame:CGRectMake(0, imageViewSearch.bottomEdge, ActualWidth(50), ActualHeight(20))];
    labelSearch.text = @"查找";
    labelSearch.textColor = TitleColor;
    [btnSearch addSubview:imageViewSearch];
    [btnSearch addSubview:labelSearch];
    
    headerView.backgroundColor = Color(0xF1F3F3);
    [headerView addSubview:self.labelFrom];
    [headerView addSubview:btnFrom];
    [headerView addSubview:labelText];
    [headerView addSubview:self.labelTo];
    [headerView addSubview:btnTo];
    [headerView addSubview:btnSearch];
    [self.view addSubview:headerView];
    //tableview
    [self.view addSubview:self.balanceSearchList];
    
    
    [self setRefresh];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self.dataSource removeAllObjects];
    [self.balanceSearchList reloadData];
    self.pageNo = 1;
    if (self.isFirst) {
        [self getTodayWithString:@"" start:@"" end:@""];
    }else{
        if (self.isSearchByDate) {
            [self getTodayWithString:@"" start:self.labelFrom.contentText end:self.labelTo.contentText];
        } else {
            [self getTodayWithString:self.searchText.text start:@"" end:@""];
        }
    }
    self.isFirst = NO;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //[self didClickCellWithRO_NO:@"201612-0007" type:0];
    
}

//默认支持大写
- (void)textFiledEditChanged:(NSNotification *)obj {
    UITextField *textField = obj.object;
    NSString *toBeString = textField.text;
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            textField.text= toBeString.uppercaseString;
        }else{
            // 有高亮选择的字符串
        }
    }else {
        textField.text = textField.text.uppercaseString;
    }
}

#pragma mark -- 添加上拉加载
- (void)setRefresh {
    __weak ICMBalanceResearchViewController *my = self;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (self.hasNext) {
            self.pageNo++;
            if (self.isSearchByDate) {
                [my getTodayWithString:@"" start:self.labelFrom.contentText end:self.labelTo.contentText];
            } else {
                [my getTodayWithString:self.searchText.text start:@"" end:@""];
            }
            
        } else {
            [self.balanceSearchList.mj_footer endRefreshingWithNoMoreData];
        }
    }];
    
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    [footer setTitle:@"正在加载" forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多数据了" forState:MJRefreshStateNoMoreData];
    self.balanceSearchList.mj_footer = footer;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSMutableArray *)dataSource{
    if(!_dataSource){
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
    
}

- (UITableView *)balanceSearchList{
    if(!_balanceSearchList){
        _balanceSearchList = [[UITableView alloc]initWithFrame:CGRectMake(0, ActualHeight(135)+1, ScreenWidth, ScreenHeight-ActualHeight(135))];
        _balanceSearchList.delegate = self;
        _balanceSearchList.dataSource = self;
        _balanceSearchList.backgroundColor = BackgroundColor_White;
        [_balanceSearchList registerClass:[ICMBalanceResearchViewCell class] forCellReuseIdentifier:@"ICMBalanceResearchViewCell"];
        _balanceSearchList.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 1)];
        _balanceSearchList.tableFooterView.backgroundColor = [UIColor whiteColor];
        _balanceSearchList.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _balanceSearchList;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ICMProxySearchModel *model = self.dataSource[indexPath.row];
    //    model.proxyID
    ICrEAMUser *user = [ICrEAMUser shareICrEAMUser];
    NSString *isMaster = [ICrEAMTool getCodeModelForCode:user.IS_SERVICE_ADVISOR_MASTER].desc;
    if([model.IS_BALANCED isEqualToString:ICMEnumIntToString(ICMEnumYESOrNOYES)])
    {
        //是总监或者服务顾问是自己才可以结算
        if(([isMaster isEqualToString:@"是"]|| [user.employee_NO isEqualToString:model.assistantCode]))
        {
            [self didClickCellWithRO_NO:model.proxyID type:@"0"];
        }else{
            [self.view showString:@"您不能操作其他服务顾问的数据" forSeconds:1.5];
        }
    }else{
        [self.view showString:@"请在PC端进行结算!" forSeconds:1.5];
    }
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ICMBalanceResearchViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ICMBalanceResearchViewCell"];
    if (!cell) {
        cell = [[ICMBalanceResearchViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ICMBalanceResearchViewCell"];
    }
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell updateDataWithBalanceModel:[self.dataSource objectAtIndex:indexPath.row]];
    return cell;
}


- (void)tableView:(UITableView *)tableView{
    
}

#pragma mark -- 时间代理
- (void)calendarView:(PACACalendarView *)calendarView didSelectedDate:(NSDate*)selectedDate{
    if(calendarView == self.pickerFrom){
        self.selectedDateFrom = selectedDate;
        NSString *dateString = [selectedDate separatorStyleDateTimeString];
        self.labelFrom.contentTextFeild.text = dateString;
    }else{
        self.selectedDateTo = selectedDate;
        NSString *dateString = [selectedDate separatorStyleDateTimeString];
        self.labelTo.contentTextFeild.text = dateString;
    }
}

#pragma mark -- 清空时间
- (void)delTime:(PACACalendarView *)calendarView
{
    if(calendarView == self.pickerFrom){
        self.selectedDateFrom = nil;
        self.labelFrom.contentTextFeild.text = @"";
    }else{
        self.selectedDateTo = nil;
        self.labelTo.contentTextFeild.text = @"";
        
    }
}

- (PACACalendarView *)pickerFrom{
    if(!_pickerFrom){
        _pickerFrom = [PACACalendarView createCalendarViewWithDidSelectedDate:nil minDate:nil maxDate:nil andFrame:CGRectMake(ScreenWidth/2-150, ScreenHeight/2-150, ActualWidth(300), ActualWidth(380))];
        _pickerFrom.delegate = self;
        
    }
    return _pickerFrom;
}
- (PACACalendarView *)pickerTo{
    if(!_pickerTo){
        _pickerTo = [PACACalendarView createCalendarViewWithDidSelectedDate:nil minDate:nil maxDate:nil andFrame:CGRectMake(ScreenWidth/2-150, ScreenHeight/2-150, ActualWidth(300), ActualWidth(380))];
        _pickerTo.delegate = self;
        
    }
    return _pickerTo;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return ActualHeight(95);
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    self.isSearchByDate = NO;
    [self.dataSource removeAllObjects];
    self.pageNo = 1;
    [self getTodayWithString:textField.text start:@"" end:@""];
    [textField resignFirstResponder];
    return YES;
}


- (void)searchByDate{
    if(!self.labelFrom.contentText || [self.labelFrom.contentText isEqualToString:@""])
    {
        [self.view showString:@"开始时间未输入!" forSeconds:1.5f];
        return;
    }
    if(!self.labelTo.contentText || [self.labelTo.contentText isEqualToString:@""])
    {
        [self.view showString:@"结束时间未输入!" forSeconds:1.5f];
        return;
    }
    
    self.isSearchByDate = YES;
    [self.dataSource removeAllObjects];
    self.pageNo = 1;
    [self getTodayWithString:@"" start:self.labelFrom.contentText end:self.labelTo.contentText];
}
- (void)clickCalenderBtnFrom{
    [Window addSubview:self.pickerFrom];
}
- (void)clickCalenderBtnTo{
    [Window addSubview:self.pickerTo];
}
- (void)didClickPreViewWithIndex:(NSIndexPath *)index{
    ICMProxySearchModel *model = self.dataSource[index.row];
    ICrEAMUser *user = [ICrEAMUser shareICrEAMUser];
    NSString *isMaster = [ICrEAMTool getCodeModelForCode:user.IS_SERVICE_ADVISOR_MASTER].desc;
    if([model.IS_BALANCED isEqualToString:ICMEnumIntToString(ICMEnumYESOrNOYES)])
    {
        //是总监或者服务顾问是自己才可以结算
        if(([isMaster isEqualToString:@"是"] || [user.employee_NO isEqualToString:model.assistantCode]))
        {
            [self didClickCellWithRO_NO:model.proxyID type:@"1"];
        }else{
            [self.view showString:@"您不能操作其他服务顾问的数据" forSeconds:1.5];
        }
    }else{
        [self.view showString:@"请在PC端进行结算!" forSeconds:1.5];
    }
}

#pragma mark -- 获取结算列表接口
- (void)getTodayWithString:(NSString *)text start:(NSString *)start end:(NSString *)end {
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:text forKey:@"QUERY_CONDITION"];
    [parameters setObject:start forKey:@"START_DATE"];
    [parameters setObject:end forKey:@"END_DATE"];
    [parameters setObject:@(self.pageNo) forKey:@"CURRENT_PAGE"];
    [manager startGetRequestWithURL:QueryRepairOrderForBalance parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        if ([data[@"CODE"] integerValue] == 200) {
            if (IsArr(data[@"TT_REPAIR_ORDER"])) {
                if(self.pageNo == 1)
                {
                    [self.dataSource removeAllObjects];
                }
                self.balanceSearchList.mj_footer.hidden = NO;
                NSArray *dataArray = data[@"TT_REPAIR_ORDER"];
                for (NSDictionary *dic in dataArray) {
                    ICMProxySearchModel *model = [ICMProxySearchModel yy_modelWithDictionary:dic];
                    [self.dataSource addObject:model];
                }
                self.hasNext = YES;
                [self.balanceSearchList.mj_footer endRefreshing];
            } else {
                if (self.dataSource.count == 0) {
                    self.balanceSearchList.mj_footer.hidden = YES;
                    [self.view showString:@"暂无相关搜索结果" forSeconds:1.5];
                } else {
                    self.hasNext = NO;
                    [self.balanceSearchList.mj_footer endRefreshingWithNoMoreData];
                }
            }
            [self.balanceSearchList reloadData];
        } else {
            [self.balanceSearchList.mj_footer endRefreshing];
        }
    }];
}

//0跳结算详情 1跳结算
#pragma mark -- 点击详情接口
- (void)didClickCellWithRO_NO:(NSString *)RO_NO type:(NSString *)type{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:RO_NO forKey:@"RO_NO"];
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    [manager startGetRequestWithURL:RepairOrderDetils parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        
        ICMBalanceBasicInfoModel *basicModel = [[ICMBalanceBasicInfoModel alloc]init];
        if (IsArr(data[@"TT_REPAIR_ORDER"])) {
            basicModel = [ICMBalanceBasicInfoModel yy_modelWithDictionary:data[@"TT_REPAIR_ORDER"][0]];
        }
        if(IsArr(data[@"TT_HQ_MEMBER"])){
            basicModel.MEMBER_PROPERTY_NAME = data[@"TT_HQ_MEMBER"][0][@"MEMBER_PROPERTY"];
            basicModel.CARD_TYPE_NAME = data[@"TT_HQ_MEMBER"][0][@"CARD_TYPE"];
        }
        
        ICMRepairMaintenancesModel *repairMaintenancesModel = [ICMRepairMaintenancesModel yy_modelWithDictionary:data];
        [repairMaintenancesModel createRepairMaintenanceRoModel];
        ICMRepairPartsArrayModel *repairPartsArrayModel = [ICMRepairPartsArrayModel yy_modelWithDictionary:data];
        [repairPartsArrayModel createRepairPartsRoModel];
        
        ICMBalanceViewController *BVC = [[ICMBalanceViewController alloc]init];
        BVC.basicModel = basicModel;
        BVC.repairMaintenancesModel = repairMaintenancesModel;
        BVC.repairPartsArrayModel = repairPartsArrayModel;
        [self.navigationController pushViewController:BVC animated:YES];
        //跳转
        //        if ([type integerValue] == 0) {
        //            ICMProxyHomePageViewController *HPVC = [[ICMProxyHomePageViewController alloc]init];
        //            HPVC.repairMaintenancesModel = repairMaintenancesModel;
        //            HPVC.proxyBasicInfoModel =basicModel;
        //            HPVC.repairPartsArrayModel = repairPartsArrayModel;
        //            HPVC.activityModels = self.activityModels;
        //            [self.navigationController pushViewController:HPVC animated:YES];
        //        }else{
        //            ICMProxyPreviewViewController *PVC = [[ICMProxyPreviewViewController alloc]init];
        //            PVC.activityModels = self.activityModels;
        //            PVC.repairMaintenancesModel = repairMaintenancesModel;
        //            PVC.proxyBasicInfoModel = basicModel;
        //            PVC.repairPartsArrayModel = repairPartsArrayModel;
        //            [self.navigationController pushViewController:PVC animated:YES];
        //        }
        
        
    }];
}




@end
